package com.ytktt.study.week12.task7.service;

import com.ytktt.study.week12.task7.entity.OrderEntity;
import com.ytktt.study.week12.task7.entity.OrderMqInfoEntity;
import com.ytktt.study.week12.task7.mapper.OrderMapper;
import com.ytktt.study.week12.task7.mapper.OrderMqInfoMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * TODO
 *
 * @author ytk
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderMqInfoMapper orderMqInfoMapper;

    @Value("${retryCount}")
    private int retryCount;

    @Override
    public void batchUpdateOrderStatus(int region) {
        Long oldSuccessMaxId = this.orderMqInfoMapper.selectSuccessMaxIdByRegion(region);
        List<OrderEntity> list = this.orderMapper.selectByTaskRegionAndStatus(region, (byte) 0, oldSuccessMaxId == 0 ? null : oldSuccessMaxId);
        long successMaxId = 0L;
        for (OrderEntity entity : list) {
            entity.setStatus((byte) 1);
            int i = 0, effectRow = 0;
            do {
                effectRow = this.orderMapper.updateOrderStatus(entity);
                ++i;
            } while (i < retryCount && effectRow != 1);
            if (effectRow == 1) {
                successMaxId = entity.getId();
            }
        }
        if (successMaxId > 0) {
            this.orderMqInfoMapper.updateSuccessMaxId(region, successMaxId);
        }
    }
}
